package com.example.anni.zhuzhoujia.bogege;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;
import com.lhh.ptrrv.library.PullToRefreshRecyclerView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 张钧博 on 2016/6/4.
 * <p/>
 * 用viewSwitch更好
 */
public class HotFragment extends Fragment {
    private String[] newsTypes = {
            "HOT", "IMPORTANT", "YL", "MS", "SZ", "LS", "WHT", "FACT"
    };
    private int index;

    public HotFragment(int index) {
        this.index = index;
    }

    public HotFragment() {
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    private View rootView;//缓存Fragment view
    //
    private TextView tvTitle;
    private PullToRefreshRecyclerView mPtrrv;
    private static final int DEFAULT_ITEM_SIZE = 10;
    private static final int ITEM_SIZE_OFFSET = 5;
    private static final int MSG_CODE_REFRESH = 0;
    private static final int MSG_CODE_LOADMORE = 1;
    private static final int TIME = 1000;
    private TotalCommentAdapter mAdapter;
    JSONArray datas;
    private List<Map<String, String>> commentList;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.hot_fragment, null);
        return rootView;
    }

    /**
     * 创建后所做的动作
     *
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        x.view().inject(getActivity());

        login();
        readData();
        mPtrrv = (PullToRefreshRecyclerView) view.findViewById(R.id.lv_news);
        mPtrrv.setSwipeEnable(true);
        initView();

    }

    /**
     * 读取远程数据
     */
    private void readData() {
        commentList = new ArrayList<>();
        RequestParams params = new RequestParams(
                "http://tr.zzapi.gson.cn/api/news/list?type=" + newsTypes[index] + "&page=1&rows=30");
        params.addBodyParameter("username", "账号");
        params.addBodyParameter("password", "密码");
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String s) {
                //Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
                JSONObject jsonObject = JSON.parseObject(s);
                datas = jsonObject.getJSONArray("data");

                for (int i = 0; i < datas.size(); i++) {
                    Map<String, String> map = new HashMap<String, String>();
                    JSONObject object = datas.getJSONObject(i);
                    String newsTitle = object.getString("title");
                    String newsSunmmary = object.getString("summary");
                    String newsCommentNum = object.getString("commentNum");
                    String newsCover = object.getString("cover");
                    String newsId = object.getInteger("id") + "";
                    String fromUrl = object.getString("fromUrl");

                    map.put("newsTitle", newsTitle);
                    map.put("newsSunmmary", newsSunmmary);
                    map.put("newsCommentNum", newsCommentNum);
                    map.put("newsCover", newsCover);
                    map.put("newsId", newsId);
                    map.put("fromUrl", fromUrl);

                    commentList.add(map);
                }
                mAdapter = new TotalCommentAdapter(getContext(), commentList);
                if (datas.size() < 10) {
                    mAdapter.setCount(datas.size());
                } else {
                    mAdapter.setCount(DEFAULT_ITEM_SIZE);
                }
                mPtrrv.setAdapter(mAdapter);
                mAdapter.setOnItemClickListener(new TotalCommentAdapter.OnRecyclerViewItemClickListener() {

                    @Override
                    public void onItemClick(View view, Integer position) {
                        Intent intent = new Intent(getActivity(), SeeNewsActivity.class);
                        intent.putExtra("newsId", (CharSequence) commentList.get(position).get("newsId"));
                        intent.putExtra("newsTitle", (CharSequence) commentList.get(position).get("newsTitle"));
                        intent.putExtra("newsCover", (CharSequence) commentList.get(position).get("newsCover"));
                        intent.putExtra("newsSunmmary", (CharSequence) commentList.get(position).get("newsSunmmary"));
                        intent.putExtra("fromUrl", (CharSequence) commentList.get(position).get("fromUrl"));
                        startActivity(intent);
                    }
                });
                mPtrrv.onFinishLoading(true, false);
            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(Callback.CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initView() {
        /*mPtrrv = (PullToRefreshRecyclerView) findViewById(R.id.ptr_lv_comment);
        mPtrrv.setSwipeEnable(true);*/
        //加载条
        DemoLoadMoreView loadMoreView = new DemoLoadMoreView(getContext(), mPtrrv.getRecyclerView());
        loadMoreView.setLoadmoreString("加载中...");
        loadMoreView.setLoadMorePadding(100);
        // set the layoutManager which to use
        //mPtrrv.setLayoutManager(new LinearLayoutManager(this));
        //线性管理器
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mPtrrv.setLayoutManager(layoutManager);
        mPtrrv.setPagingableListener(new PullToRefreshRecyclerView.PagingableListener() {
            @Override
            public void onLoadMoreItems() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_LOADMORE, TIME);
            }
        });
        mPtrrv.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_REFRESH, TIME);
            }
        });
        //设置下划线
        /*mPtrrv.getRecyclerView().addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));*/
        //设置动画
        mPtrrv.getRecyclerView().setItemAnimator(new DefaultItemAnimator());

        //为什么这里会报错！！！
        //mPtrrv.addHeaderView(View.inflate(getContext(), R.layout.read_history_header, null));

        mPtrrv.setEmptyView(View.inflate(getContext(), R.layout.read_history_empty_view, null));
        mPtrrv.removeHeader();
        mPtrrv.setLoadMoreFooter(loadMoreView);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_CODE_REFRESH) {
                readData();
                mPtrrv.setOnRefreshComplete();
            } else if (msg.what == MSG_CODE_LOADMORE) {
                if (datas.size() - mAdapter.getItemCount() >= 5) {
                    mAdapter.setCount(mAdapter.getItemCount() + ITEM_SIZE_OFFSET);
                    mPtrrv.onFinishLoading(true, false);
                } else if (datas.size() - mAdapter.getItemCount() < 5 && datas.size() - mAdapter.getItemCount() > 0) {
                    mAdapter.setCount(mAdapter.getItemCount() + datas.size() - mAdapter.getItemCount());
                    Log.e("mAdapter", mAdapter.getItemCount() + datas.size() - mAdapter.getItemCount() + "");
                    mPtrrv.onFinishLoading(true, false);
                } else if (datas.size() - mAdapter.getItemCount() < 0) {
                    mAdapter.setCount(datas.size());
                } else {
                    //Log.e("mAdapter", "没有更多加载"+"");
                    //over
                    Toast.makeText(getContext(), "没有更多加载", Toast.LENGTH_SHORT).show();
                    mPtrrv.onFinishLoading(false, false);
                }
            }
        }
    };

    /**
     * 登录
     */
    private void login() {
        RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/user/login");
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = sp.getString("userName", "");
        String password = sp.getString("password", "");
        params.addBodyParameter("userName", userName);
        params.addBodyParameter("password", password);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {

            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /*pullToRefreshRecyclerView适配器*/
    static class TotalCommentAdapter extends RecyclerView.Adapter<MyViewHolder> implements View.OnClickListener {
        private List<Map<String, String>> commentList;
        private Context mContext;
        private LayoutInflater mInflater;
        protected int mCount = 0;

        public void setCount(int count) {
            this.mCount = count;
        }

        public TotalCommentAdapter(Context mContext, List<Map<String, String>> commentList) {
            this.commentList = commentList;
            this.mContext = mContext;
            mInflater = LayoutInflater.from(mContext);
        }

        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                //注意这里使用getTag方法获取数据
                mOnItemClickListener.onItemClick(v, (Integer) v.getTag());
            }
        }

        //最后暴露给外面的调用者，定义一个设置Listener的方法（）：
        public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
            this.mOnItemClickListener = listener;
        }

        //自定义接口 构造
        public interface OnRecyclerViewItemClickListener {
            void onItemClick(View view, Integer position);
        }

        private OnRecyclerViewItemClickListener mOnItemClickListener = null;

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.list_item, parent, false);
            MyViewHolder holder = new MyViewHolder(view);
            view.setOnClickListener(this);
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.newsTitle1.setText((String) commentList.get(position).get("newsTitle"));
            holder.tvSummary.setText((String) commentList.get(position).get("newsSunmmary"));
            holder.tvCommentnum.setText((String) commentList.get(position).get("newsCommentNum") + "跟帖");
            /**
             * 设置加载图片时等待的图片和失败的图片
             */
            ImageOptions options = new ImageOptions.Builder()
                    .setLoadingDrawableId(R.mipmap.ic_launcher)
                    .setFailureDrawableId(R.mipmap.broke_sel)
                    .build();

            x.image().bind(holder.newsCover, "http://tr.zzapi.gson.cn/" + (String) commentList.get(position).get("newsCover"), options);

            if (commentList.get(position).get("newsCover").equals("")) {
                holder.newsCover.setVisibility(View.GONE);
            } else {
                holder.newsCover.setVisibility(View.VISIBLE);
            }
            //将数据保存在itemView的Tag中，以便点击时进行获取
            holder.itemView.setTag(position);
        }

        @Override
        public int getItemCount() {
            return mCount;
        }

    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        public ImageView newsCover;
        public TextView newsTitle1;
        public TextView tvSummary;
        public TextView tvCommentnum;

        public MyViewHolder(View view) {
            super(view);
            newsCover = (ImageView) view.findViewById(R.id.news_cover);
            newsTitle1 = (TextView) view.findViewById(R.id.news_title);
            tvSummary = (TextView) view.findViewById(R.id.tv_sunmmary);
            tvCommentnum = (TextView) view.findViewById(R.id.tv_commentnum);
        }

    }

}
